package club.hicode.daydayup.redis.lettuce.queue;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import io.lettuce.core.Limit;
import io.lettuce.core.Range;
import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;

import java.util.List;

/**
 * 消息生产
 * @author Liu Chunfu
 * @date 2018-08-27 下午2:40
 **/
public class Provider {

	private static final String KEY = "d-queue";

	private RedisCommands commands;

	public Provider() {
		RedisClient redisClient = RedisClient.create("redis://@localhost:6379/0");
		StatefulRedisConnection<String, String> connection = redisClient.connect();
		this.commands = connection.sync();
	}

	public boolean task(String t, Long seconds) {
		//当前范围
		Long zadd = commands.zadd(KEY, System.currentTimeMillis() + seconds * 1000, t);
		return zadd != 0;
	}

	public void consumer() {
		//第二参数为获取的范围：应该从0开始
		List zrangebyscore = commands
				.zrangebyscore(KEY, Range.create(0, System.currentTimeMillis() + 5 * 1000), Limit.create(0, 1));
		if (CollectionUtil.isEmpty(zrangebyscore)) {
			System.out.println("next...");
			return;
		}
		Object next = zrangebyscore.iterator().next();
		String str = Convert.toStr(next);
		Long zrem = commands.zrem(KEY, str);
		if (zrem == 0) {
			System.out.println("其他线程占用了...");
			return;
		}
		System.out.println(str + "被移除！");

	}

}
